<script lang="ts">
  import { actixGraphqlEndpoint } from "$lib/js/stores";

  import type { Folder, Editor, KV,Quiz } from "$lib/ebm";
  import {
    Query,
    useQuery,
    useMutation,
    useQueryClient,
  } from "@sveltestack/svelte-query";
  import { request, gql } from "graphql-request";
  export let attributes: KV[] = [
    {
      k: "subject",
      v: "en",
    },
  ];

  let folderid = attributes.find((x) => x.k == "folder_id");
  let classPointerEventsNone;
  const onMouseDown = () => {
    classPointerEventsNone = "pointer-events-none";
  };
  const onMouseUp = () => {
    classPointerEventsNone = "";
  };
  const queryClient = useQueryClient();

  let endpoint = $actixGraphqlEndpoint;
  const FIND_FOLDER_QUERY = gql`
    query ($id: ID!) {
      folder: node(id: $id) {
        id
        createdAt
        updatedAt
        ... on Folder {
          folderName
          snapshotAt
          seq
          title
          description
          refererUrl
          ancestry
          status
          pid
          from
          quizzes {
            id
            seq
            level
            subject
            m3U8
            title
            description
            createdAt
            updatedAt
            status
            from
          }
        }
      }
    }
  `;

  const findFolderResult = useQuery<Folder, { message: string }>(
    ["folder", folderid.v],
    async () => {
      const { folder } = await request(endpoint, FIND_FOLDER_QUERY, {
        id: folderid.v,
      });
      return folder;
    }
  );

  let activeEdgeId = "";
  const handleEdgeClick = (id) => () => {
    activeEdgeId = id;
    console.log("handleEdgeClick activeEdgeId=", activeEdgeId);
  };

  const openEditorMutation = useMutation<
    Editor,
    { message: string },
    {
      id_: string;
      title_: string;
    }
  >(
    async ({ id_, title_ }) => {
      const { editor } = await request(
        endpoint,
        gql`
          mutation ($id: ID!, $title: String!) {
            editor: openEditor(input: { id: $id, title: $title }) {
              id
              snapshotAt
              title
              createdAt
              updatedAt
              status
              from
            }
          }
        `,
        {
          id: id_,
          title: title_,
        }
      );
      return editor;
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries("editors_query");
      },
    }
  );

  const openEditor = (quiz:Quiz)=>()=> {
    $openEditorMutation.mutate({
      id_: quiz.id,
      title_: quiz.title,
    });
    console.log(
      "double click to open editor for folder={}, id={}",
      quiz.title,
      quiz.id
    );
  };

  let value = "";
  const handleEdgeAddClick = (id) => () => {
    alert("handleEdgeAddClick to id=" + id + " value=" + value);
  };
</script>

{#if $findFolderResult.isLoading}
  Loading...
{:else if $findFolderResult.isError}
  Error {$findFolderResult.error.message}
{:else}
  <table class="bg-white text-gray-900 w-full shadow-none">
    <thead class="pt-4">
      <tr>
        <th colspan="4" class=" text-lg text-left">
          <i class="fas fa-arrow-alt-circle-right mx-2" />
          Edges From This Folder({$findFolderResult.data.title})
        </th>
      </tr>
      <tr>
        <th class="bg-blue-700 text-white p-2">Subject</th>
        <th class="bg-blue-700 text-white p-2">Predicate</th>
        <th class="bg-blue-700 text-white px-0">Object</th>
        <th class="bg-blue-700 text-white p-2 text-center">Ops</th>
      </tr>
    </thead>
    <tbody>
      <tr
        class="bg-blue-100 text-blue-900 hover:bg-rose-200 border-b border-teal-500 "
      >
        <td class="p-2">This</td>
        <td class="p-2">HAS_MEMBER_OF</td>
        <td class="px-0 flex flex-row items-center">
          <i class="fas fa-arrow-alt-circle-right px-2	" />
          <input
            type="text"
            class="pl-4 w-full"
            name="title"
            bind:value
            placeholder="Input Title To New Quiz"
            on:keydown={(e) =>
              e.detail === 13 && handleEdgeAddClick($findFolderResult.data.id)}
          />
        </td>
        <td class="p-2 text-center"
          >
          <i
            class="far fa-plus-circle cursor-pointer"
            on:click={handleEdgeAddClick($findFolderResult.data.id)}
          />
          </td
        >
      </tr>

      {#each $findFolderResult.data.quizzes as quiz}
        <tr
          class="{activeEdgeId === quiz.id
            ? 'bg-rose-400'
            : 'bg-blue-100'} text-blue-900 hover:bg-rose-200 border-b border-teal-500 "
          on:click={handleEdgeClick(quiz.id)}
          on:dblclick={openEditor(quiz)}
        >
          <td class="p-2">This</td>
          <td class="p-2">HAS_MEMBER_OF</td>
          <td class="px-0"
            ><i
              class="fas fa-arrow-alt-circle-right px-2"
            />{quiz.title}-{quiz.id}</td
          >
          <td class="p-2 text-center">
            <i class="far fa-trash-alt cursor-pointer" />
          </td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}
